<?php
require_once 'vendor/autoload.php';


date_default_timezone_set('Asia/Shanghai');


$pidPath = __DIR__.DIRECTORY_SEPARATOR.'pid';
$options = getopt('r:q::f::');


if (empty($options['r'])) {
    die('缺少房间号');
}
if (empty($options['q'])) {
    $options['q'] = 150;
}

$roomId = $options['r'];
$quality = $options['q'];
$debug = isset($options['debug']);
$format = isset($options['f']) ? $options['f'] : 'default';

set_exception_handler(function (\Throwable $throwable)use($debug) {


        if ($throwable instanceof \GuzzleHttp\Exception\TransferException) {
            echo 'Request:' . PHP_EOL;
            print_r($throwable->getRequest()->getHeaders());
            print_r($throwable->getRequest()->getBody());
            if ($throwable instanceof \GuzzleHttp\Exception\RequestException) {
                echo 'Response:' . PHP_EOL;
                echo $throwable->getResponse()->getStatusCode().PHP_EOL;
                print_r($throwable->getResponse()->getHeaders());
                echo $throwable->getResponse()->getBody().PHP_EOL;
            }
        }



        echo 'Message:'.$throwable->getMessage().PHP_EOL;
        echo 'Code:'.$throwable->getCode().PHP_EOL;
        echo 'File:' . $throwable->getFile().PHP_EOL;
        echo 'Line:'.$throwable->getLine().PHP_EOL;
        echo 'Trace:'.$throwable->getTraceAsString().PHP_EOL;

    echo 'EXIT '.date("Y-m-d H:i:s").PHP_EOL;
});

$client = new BilibiliClient([
    'debug' => $debug
]);

$r = $client->room_v1_room_get_info($roomId);

if (intval($r['code']) !== 0) {
    throw new \Exception( "$roomId 接口返回错误：{$r['message']}");
}

if (intval($r['data']['live_status']) !== 1) {
    throw new \Exception("$roomId 主播未开播");
}

$roomId = $r['data']['room_id']; // 真实房间id

$title = $r['data']['title'];


if (!file_exists($pidPath)) {
    mkdir($pidPath);
}
file_put_contents($pidPath . DIRECTORY_SEPARATOR . $roomId, getmypid());

$r = $client->xlive_web_room_v2_index_getRoomPlayInfo($roomId, $quality);

if (intval($r['code']) !== 0 || empty($r['data']['playurl_info'])) {
    throw new \Exception("$roomId 获取直播地址失败 {$r['message']}");
}



$baseSavedFile = str_replace(['(', ')', ' ', '/', ':', '*', '?', '<', '>', '|', '"'], '', $title) . '_' . date('YmdHis');

$i = 0;


$streams = $r['data']['playurl_info']['playurl']['stream'];
if ($format !== 'default') {
    foreach ($streams as $k=> $stream) {
        if ($stream['format'][0]['format_name'] === $format) {
            $i = $k;
        }
    }
}


        switch ($streams[$i]['format'][0]['format_name']) {
            case 'fmp4':

                $a = $streams[$i]['format'][0]['codec'][0];
                $liveUrl = $a['url_info'][0]['host'] .$a['base_url'];
                $savedFile = $baseSavedFile . '.ts';
                $client->getM3U8IndexV2($liveUrl,$savedFile,$roomId);

                break;

            case 'flv':
                $a = $streams[$i]['format'][0]['codec'][0];
                $liveUrl = $a['url_info'][0]['host'] .$a['base_url'].$a['url_info'][0]['extra'];
                $savedFile = $baseSavedFile . '.flv';
                $client->storeStreamData($client->getFLVStream($liveUrl)->getBody(), $savedFile);
                break;
        }


if (PHP_OS === 'Linux') {
    echo date('Y-m-d H:i:s') . ':start upload' .PHP_EOL;
    shell_exec("nohup sh /usr/local/liverecord/upload.sh {$savedFile} 2>&1 &");
    echo date('Y-m-d H:i:s') . ':commit upload task' .PHP_EOL;
}
echo date('Y-m-d H:i:s') . ':finished' .PHP_EOL;
